import html2canvas from "html2canvas";
import jsPDF from "jspdf";

export const downloadPDF = (page, name) => {
  return new Promise((resolve, reject) => {
    html2canvas(page, {
      useCORS: true, //允许canvas画布内 可以跨域请求外部链接图片, 允许跨域请求。
      allowTaint: true, //允许跨域
      scale: 2, //设置放大倍数
      backgroundColor: "#ffffff", //背景色
    })
      .then((canvas) => {
        canvas2PDF(canvas, name);
        resolve(true);
      })
      .catch((err) => {
        reject(err);
      });
  });
};

const canvas2PDF = (canvas, name = "合同") => {
  // 新建JsPDF对象
  const PDF = new jsPDF({
    orientation: "p", //参数： l：横向  p：纵向
    unit: "mm", //参数：测量单位（"pt"，"mm", "cm", "m", "in" or "px"）
    format: "a4", //A4纸
  });
  const ctx = canvas.getContext("2d");
  const a4w = 190;
  const a4h = 277; //A4大小，210mm x 297mm，四边各保留10mm的边距，显示区域190x277
  const imgHeight = Math.floor((a4h * canvas.width) / a4w); //按A4显示比例换算一页图像的像素高度
  let renderedHeight = 0;

  while (renderedHeight < canvas.height) {
    let page = document.createElement("canvas");
    page.width = canvas.width;
    page.height = Math.min(imgHeight, canvas.height - renderedHeight); //可能内容不足一页

    //用getImageData剪裁指定区域，并画到前面创建的canvas对象中
    page
      .getContext("2d")
      .putImageData(
        ctx.getImageData(
          0,
          renderedHeight,
          canvas.width,
          Math.min(imgHeight, canvas.height - renderedHeight)
        ),
        0,
        0
      );

    // canvas转图片数据保留10mm边距
    PDF.addImage(
      page.toDataURL("image/jpeg", 0.2),
      "JPEG",
      10,
      10,
      a4w,
      Math.min(a4h, (a4w * page.height) / page.width)
    );

    renderedHeight += imgHeight;

    //判断是否分页，如果后面还有内容，添加一个空页
    if (renderedHeight < canvas.height) {
      PDF.addPage();
    }
  }

  PDF.save(`${name}.pdf`);
};

export function markdownToHtmlSubject(contractTempContent) {
  $("#editor-subject").html(
    '<textarea id="appendSubject" style="display:none;"></textarea>'
  );
  $("#appendSubject").val(contractTempContent); //将需要转换的内容加到转换后展示容器的textarea隐藏标签中
  //先对容器初始化，在需要展示的容器中创建textarea隐藏标签，
  editormd.markdownToHTML("editor-subject", {
    htmlDecode: "style,script,iframe",
    emoji: true,
    taskList: true,
    tocm: true,
    tex: true, // 默认不解析
    flowChart: true, // 默认不解析
    sequenceDiagram: true, // 默认不解析
    codeFold: true,
  });
}
